package com.hbase_mapreduce.write;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

/**
 * ImmutableBytesWritable 写出到Hbase的key的类型
 * mapreduce往Hbase写数据的时候，key是使用不到的，write的时候，key直接给null就可以了
 */
public class MyReducer extends TableReducer<Text, IntWritable, ImmutableBytesWritable> {

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        int sum = 0;
        Iterator<IntWritable> iterator = values.iterator();
        while (iterator.hasNext()) {
            // 等同于下面的遍历效果
            IntWritable value = iterator.next();
            sum += value.get();
        }
        // 使用Hbase api构建put对象，设置写入的数据
        Put put = new Put(key.toString().getBytes());
        put.addColumn("info".getBytes(), "ct".getBytes(), (sum + "").getBytes());
        context.write(null, put);
    }
}
